/*
 *
 *  * Copyright (c) iwindplus Technologies Co., Ltd.2024-2030, All rights reserved.
 *
 *
 */

package com.iwindplus.im.server.strategy.context;

import com.iwindplus.base.domain.exception.BizException;
import com.iwindplus.im.domain.dto.WsSendMsgDTO;
import com.iwindplus.im.domain.enums.CommandEnum;
import com.iwindplus.im.domain.enums.ImCodeEnum;
import com.iwindplus.im.server.strategy.WsMsgStrategy;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.tio.core.ChannelContext;

/**
 * websocket 消息策略上下文.
 *
 * @author zengdegui
 * @since 2025/09/21 20:21
 */
@Slf4j
@Component
public class WsMsgStrategyContext {

    private final Map<CommandEnum, WsMsgStrategy> strategyMap;

    /**
     * 构造函数.
     *
     * @param strategies 策略列表
     */
    public WsMsgStrategyContext(List<WsMsgStrategy> strategies) {
        strategyMap = strategies.stream()
            .collect(Collectors.toMap(WsMsgStrategy::support, Function.identity()));
    }

    /**
     * 发送消息.
     *
     * @param entity 消息实体
     * @param ctx    通道上下文
     */
    public void send(WsSendMsgDTO entity, ChannelContext ctx) {
        WsMsgStrategy strategy = strategyMap.get(entity.getCommand());
        if (strategy == null) {
            throw new BizException(ImCodeEnum.INVALID_MSG_COMMAND);
        }

        strategy.send(entity, ctx);
    }
}
